package com.example.server.fix;

import com.example.server.config.NacosConfigLocalCatch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import quickfix.ConfigError;
import quickfix.DefaultMessageFactory;
import quickfix.FileStoreFactory;
import quickfix.LogFactory;
import quickfix.MessageFactory;
import quickfix.MessageStoreFactory;
import quickfix.ScreenLogFactory;
import quickfix.SessionID;
import quickfix.SessionSettings;
import quickfix.ThreadedSocketAcceptor;

import javax.annotation.PostConstruct;

@Service
public class FixAcceptor {


    private static ThreadedSocketAcceptor acceptor;
    private static SessionSettings settings;

    @Autowired
    private NacosConfigLocalCatch configLocalCatch;

    @Autowired
    private FixAcceptorApplication application;

    public static ThreadedSocketAcceptor getAcceptor() {
        return acceptor;
    }

    public static void main(String[] args) {
        FixAcceptor fixAcceptor = new FixAcceptor();
        fixAcceptor.startServer();

        // 启动一个Session，记得参考你的quickfix.properties设定
        SessionID sessionID = new SessionID("FIX.4.4", "QUICKFIX_ACCEPTOR", "QUICKFIX_INITIATOR1");

        while (true) {
            // 等消息就行了
        }
    }

    public void initialize() {
        try {

//            String fixServer = configLocalCatch.get("fixServer", String.class);
//            InputStream serverConfig = new ByteArrayInputStream(fixServer.getBytes(StandardCharsets.UTF_8));
//            settings = new SessionSettings(serverConfig);
            settings = new SessionSettings("quickfix.properties");

        } catch (ConfigError configError) {
            System.out.println("Warning: config error!" + configError);
        }

        MessageStoreFactory storeFactory = new FileStoreFactory(settings);
        LogFactory logFactory = new ScreenLogFactory(settings);
        MessageFactory messageFactory = new DefaultMessageFactory();
        try {
            acceptor = new ThreadedSocketAcceptor(application, storeFactory, settings, logFactory, messageFactory);
        } catch (ConfigError configError) {
            System.out.println("Warning: config error! " + configError);
        }
    }

    @PostConstruct
    public void startServer() {
        try {
            System.out.println("服务启动中。。。。。");
            initialize();
            acceptor.start();
            // acceptor.stop();
            System.out.println("服务启动完成。。。。。");
        } catch (ConfigError configError) {
            configError.printStackTrace();
        }
    }

    private void stopServer() {
        acceptor.stop();
    }


}
